package cn.net.isir.common;

import cn.net.isir.core.JedisManager;

import java.util.Map;
import java.util.Set;

/**
 * @author liuxubo
 * @filename CacheObjectHandle.java
 * @package cn.net.isir.common
 * @email lxb@isir.net.cn
 * @date 2019/03/06
 * @comment
 * @since 1.8
 */
public class CacheObjectHandle {

    private String prefix;
    private static JedisManager jedisManager = null;

    public String getPrefix() {
        return prefix;
    }

    protected CacheObjectHandle(String prefix, JedisManager jedisManager) {
        this.prefix = prefix;
        if (CacheObjectHandle.jedisManager == null) {
            CacheObjectHandle.jedisManager = jedisManager;
        }
    }

    /**
     * 设置缓存
     *
     * @param key   键
     * @param value 值
     */
    public void set(String key, String value) {
        jedisManager.set(prefix + key, value);
    }

    /**
     * 获取缓存
     *
     * @param key 键
     */
    public String get(String key) {
        return jedisManager.get(prefix + key);
    }

    /**
     * 设置缓存过期时间
     *
     * @param key     键
     * @param seconds 过期时间(秒)
     */
    public void expire(String key, int seconds) {
        if (seconds != 0) {
            jedisManager.expire(prefix + key, seconds);
        }
    }


    /**
     * 移除键对应的值
     *
     * @param key 键
     */
    public void delete(String key) {
        if (get(key) != null) {
            jedisManager.delete(prefix + key);
        }
    }

    /**
     * 获取所有相关的键
     *
     * @return map键列表
     */
    public Set<String> getKeys() {
        return jedisManager.getKeys(prefix + "*");
    }

    /**
     * 获取所有相关的键值对
     *
     * @return map键值对列表
     */
    public Map<String, Object> getEntityMap() {
        return jedisManager.getEntityMap(prefix + "*");
    }
}
